(function () {
    const wv = window.chrome?.webview;
    const $ = s => document.querySelector(s);
    const $$ = s => document.querySelectorAll(s);

    let currentSessionId = newId();
    function newId() { return Array.from(crypto.getRandomValues(new Uint8Array(8))).map(x => x.toString(16).padStart(2, '0')).join(''); }
    function send(msg) { wv?.postMessage(JSON.stringify(msg)); }

    /**
     * 每次追加消息的位置后面都滚动一下（基础滚动）
     */
    function scrollToBottom() {
        const box = document.querySelector('#messages');
        if (!box) return;
        box.scrollTop = box.scrollHeight;
    }

    /** 基于 rAF 的轻微节流，避免流式高频抖动 */
    let _scrollTick = null;
    function scrollSmooth() {
        if (_scrollTick) return;
        _scrollTick = requestAnimationFrame(() => {
            scrollToBottom();
            _scrollTick = null;
        });
    }

    /** 判断是否接近底部（用户如果在回看历史就不抢滚动） */
    function isNearBottom() {
        const box = document.querySelector('#messages');
        if (!box) return true;
        const threshold = 40; // 距底部 40px 内算“在底部附近”
        return (box.scrollHeight - box.scrollTop - box.clientHeight) < threshold;
    }

    function renderSessions(items) {
        const box = $('#sessions'); box.innerHTML = '';
        items.forEach(it => {
            const div = document.createElement('div');
            div.className = 'session-item' + (it.id === currentSessionId ? ' active' : '');
            div.textContent = it.title || ('会话 ' + it.id.slice(0, 6));
            div.onclick = () => {
                currentSessionId = it.id;
                $('#sessionTitle').textContent = '会话 ' + currentSessionId.slice(0, 6);
                send({ type: 'openSession', sessionId: currentSessionId });
                $$('.session-item').forEach(el => el.classList.remove('active'));
                div.classList.add('active');
            };
            box.appendChild(div);
        });
    }

    function addMessage(role, text, streaming = false) {
        const m = document.createElement('div');
        m.className = 'msg ' + role + (streaming ? ' streaming' : '');
        m.textContent = text || '';
        const box = $('#messages');
        box.appendChild(m);
        // 仅当用户在底部附近时才自动滚动（防止阅览历史被打断）
        if (isNearBottom()) scrollSmooth();
        return m;
    }

    $('#newChat').onclick = () => {
        currentSessionId = newId();
        $('#sessionTitle').textContent = '会话 ' + currentSessionId.slice(0, 6);
        $('#messages').innerHTML = '';
        $('#prompt').value = '';
        renderSessions([{ id: currentSessionId, title: '会话 ' + currentSessionId.slice(0, 6) }]);
        // 新会话后滚到底（其实是空列表，兼容后续首条消息）
        scrollToBottom();
    };

    function doSend() {
        const t = $('#prompt').value.trim();
        if (!t) return;
        $('#prompt').value = '';
        send({ type: 'ask', text: t, sessionId: currentSessionId });
    }
    $('#send').onclick = doSend;
    $('#prompt').addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            doSend();
        }
    });
    $('#clear').onclick = () => { $('#prompt').value = ''; };

    wv?.addEventListener('message', ev => {
        const data = JSON.parse(ev.data || '{}');
        if (data.type === 'sessions') {
            renderSessions(data.items || []);

        } else if (data.type === 'loadSession') {
            currentSessionId = data.sessionId;
            const box = $('#messages');
            box.innerHTML = '';
            (data.messages || []).forEach(m => addMessage(m.role, m.content));
            // 加载历史后滚到底
            scrollToBottom();

        } else if (data.type === 'addUserMessage') {
            addMessage('user', data.content);

        } else if (data.type === 'startAssistantMessage') {
            // 开始新一条 AI 消息（流式），先插入空容器
            window._streamEl = addMessage('assistant', '', true);

        } else if (data.type === 'appendAssistantChunk') {
            if (window._streamEl) {
                const wasNearBottom = isNearBottom();
                window._streamEl.textContent += data.content || '';
                if (wasNearBottom) scrollSmooth();
            }

        } else if (data.type === 'finishAssistantMessage') {
            if (window._streamEl) {
                window._streamEl.classList.remove('streaming');
                window._streamEl = null;
                scrollSmooth();
            }

        } else if (data.type === 'addAssistantMessage') {
            addMessage('assistant', data.content);
        }
    });

    // 初始加载
    send({ type: 'loadSessions' });
    $('#sessionTitle').textContent = '会话 ' + currentSessionId.slice(0, 6);

    // 视口变化时也尽量保持在底部（用户若正在查看历史不会强制滚）
    window.addEventListener('resize', () => {
        if (isNearBottom()) scrollSmooth();
    });
})();
